﻿using LS.Nc6.Web.Entry.ViewModel.UI;

namespace LS.Nc6.Web.Entry.ViewComponents
{
    public class HeaderViewComponent:ViewComponent
    {
        private readonly ICmsChannelService _cmsChannelService;
        private readonly ICmsContentService _contentService;
        public HeaderViewComponent(ICmsChannelService cmsChannelService, ICmsContentService contentService)
        {
            _cmsChannelService= cmsChannelService;
            _contentService= contentService;
        }
        public  async Task<IViewComponentResult> InvokeAsync()
        {
            var channellist = await _cmsChannelService.List(a => true, a => a.Taxis);
            var channelhomelist = channellist.Where(w => w.ParentId == 1);
            List<NavItemVM> lsetm = new List<NavItemVM>();
            foreach (var item in channelhomelist)
            {
                NavItemVM etm = new NavItemVM();
                etm.Id = item.Id;
                etm.NavName = item.ChannelName;
                etm.NavIndex = item.IndexName;
                etm.LinkTypeEnum = (LinkType)Enum.Parse(typeof(LinkType),item.LinkType);
                etm.LinkUrl = item.LinkUrl;
                if (etm.LinkTypeEnum == LinkType.LinkToFirstContent)
                {
                    etm.FirstContentId = (await _contentService.GetFirstModelAsync(a => true, a => a.AddTime, true))?.Id;
                }

                GetChildren(etm, channellist, item.Id);
                lsetm.Add(etm);
            }
            return View(lsetm);
        }
        private async void GetChildren(NavItemVM etm, List<CmsChannelEntity> listpartmenu, long pid)
        {
            var children = listpartmenu.Where(w => w.ParentId == pid);
            List<NavItemVM> lsetm = new List<NavItemVM>();
            if (children != null && children.Count() > 0)
            {
                foreach (var item in children)
                {
                    NavItemVM etmchildren = new NavItemVM();
                    etmchildren.Id = item.Id;
                    etmchildren.NavName = item.ChannelName;
                    etmchildren.NavIndex = item.IndexName;
                    etm.LinkTypeEnum = (LinkType)Enum.Parse(typeof(LinkType), item.LinkType);
                    etm.LinkUrl = item.LinkUrl;
                    if (etm.LinkTypeEnum == LinkType.LinkToFirstContent)
                    {
                        etm.FirstContentId =(await _contentService.GetFirstModelAsync(a => true, a => a.AddTime, true))?.Id;
                    }
                   
                    GetChildren(etmchildren, listpartmenu, item.Id);
                    lsetm.Add(etmchildren);
                }
                if (lsetm.Count > 0)
                {
                    etm.Children = lsetm;
                }
            }
        }
    }
}
